Ccay.Module.define("Ccay.SiteMap.ListSiteMap",function(page, $S) {
	
	page.ready = function() {
		$S("#btnAdd").ccayTip("ccay.sitemap.label.addTip");
		$S("#siteMapExportBtn").ccayTip("ccay.sitemap.label.exportTip");
		function permissionValid(value, ruleParams, element) {
			var igrid = $S("#listSiteMapIgrid").manager(), rowData;
			if ($.isPlainObject(element)) {
				rowData = element;
			} else {
				var td = $(element).data('caller');
				if (td && td.length) {
					var row = igrid.getCellRow(td);
					rowData = igrid.getRowData(row);
				}
			}
			if (rowData) {
				if (rowData.control == 3 && !value) {
					return $i18n("ccay.common.validate.required");
				}
			}
			return true;
		}
		var gridOption = {
			// percentWidth :true,
			// TODO
			// editPermission:"Service$SiteMap.Manage$update",
			editMode : true,
			showPager : false,
			// 设置工具栏容器
			toolPanel : "#tbrSiteMap",
			// 设置全屏容器
			fullPanel : "#dvSiteMap",
			rowRender : "tree",
			rowRenderOp : {
				parent : "parent.siteNodeId",
				field : "siteNodeId",
				showField : "name",
				sortData : true,
				select : "multi", // 单选 single
				loadDeep : 10,
				lazyLoad : true,
				parentText : "parent.name",
				ajax : {
					url : "services/manage/sitemap/tree/list?parentId={0}"
				},
				// fnCheckRoot:function(pid,node,datas){
				// return true;
				// },
				fnCheckChild : function(node) {
					return node.hasChild;
				}
			},
			contextMenu : true,
			menuOp : {
				menus : [ {
					// 导出 上下文的菜单
					text : $i18n("ccay.common.button.export"),
					click : function(cell, menu) {
						var rowData = $S("#listSiteMapIgrid").manager().getRowData(cell);
						Ccay.SiteMap.ListSiteMap.siteMapExport(rowData.siteNodeId);
					},
					fnCheck : function() {
						// 无导出权限时不显示
						return Ccay.Permission.check("Service$SiteMap.Manage$import");
					}
				} ]
			},
			showSeq : false,
			colsort : false,
			height : 380,
			allowSort : false,
			// 设置igrid编辑之后的事件
			fnEndEdit : function(value, rowData, td) {
				var currentVal = value.value || value;
				// 只有操作"显示栏目"时，非"功能可用时(3)"时，功能列置空
				if (td.attr("field") == "control" && currentVal != 3) {
					rowData.permissionString = "";
					// 防止重新渲染，修改标识丢失
					var row = this.getCellRow(td);
					row.find("td[field=permissionString]").text("");
					// return true; // 重新渲染行，但标识会丢失
				}
				;
				// rowData["parent.siteNodeId"] != null &&
				// (rowData.parent.siteNodeId =
				// rowData["parent.siteNodeId"]);
			},
			fnBeforeEdit : function(value, td, col) {
				// 得到行对象
				var row = this.getCellRow(td);
				// 得到行数据
				var rowData = this.getRowData(row);
				// 控制单元格是否可编辑
				if (rowData.control == 3 && col.field == "permissionString") {
					return true;
				}
				if (rowData.control != 3 && col.field == "permissionString") {
					return false;
				}
				if (rowData.siteNodeId == workspaceVO.leftMenuNode.siteNodeId) {
					if (col.field == "status" || col.field == "parent.name" || col.field == "control") {
						return false;
					}
				}
			},
			fnComplete : function() {
				/*
				 * var tip = $.create("a","ccay-icon
				 * help").tip({content:$i18n("ccay.sitemap.label.targetTip"),container:"#ccayContentPanel"});
				 * $S("#listSiteMapIgrid").find("td[field='target']:first").children().append(tip);
				 */
			},
			columns : [
			// {columnType: "select",multi: false},
			{
				width : 200,
				field : 'name',
				header : 'ccay.sitemap.label.name',
				freezeable : true,
				rule : {
					required : true,
					maxlength : 100,
					speczh : true
				},
				renderer : Ccay.UI.Renderer.create(showNameByLang)
			}, {
				width : 50,
				field : 'siteNodeId',
				header : 'ccay.sitemap.label.siteNodeId',
				editable : false,
				hidden : true
			}, {
				width : 100,
				field : 'parent.name',
				valueField : "parent.siteNodeId",
				header : 'ccay.sitemap.label.parentId',
				rule : {
					required : true,
					maxlength : 100
				},
				renderer : Ccay.UI.Renderer.create(showNameByLang2p),
				rendererType : 'enum',
				format : {
					valueField : "value",
					displayField : "text"
				},
				editorOp : {
					conf : {
						valueField : 'siteNodeId',
						displayField : 'name',
						title : "ccay.sitemap.selectparent",
						url : "services/manage/sitemap/all/tree",
						treeSetting : {
							expandLevel : "0",
							selectField : "siteNodeId"
						}
					}
				},
				editor : Ccay.Editor.create(popupTree)
			}, {
				width : 100,
				field : 'url',
				header : 'ccay.sitemap.label.url',
				rule : {
					maxlength : 1000
				},
				rendererType : "ellipsis",
				type : "textarea"
			},
			{
				width : 100,
				field : 'faName',
				header : 'ccay.sitemap.label.icon',
				rule : {
					maxlength : 1000
				},
				rendererType : "ellipsis",
				rule : {
					required : true
				}
			},{
				width : 50,
				field : 'orderId',
				cssName : "right",
				header : 'ccay.sitemap.label.orderId',
				rule : {
					required : true,
					digits : true,
					max : 9999999,
					min : 0
				}
			}, {
				width : 55,
				field : 'status',
				cssName : "center",
				header : 'ccay.sitemap.label.visible',
				type : 'enum',
				format : {
					service : 'FN:Ccay.SiteMap.ListSiteMap.getStatus',
					valueField : "value",
					displayField : "text"
				},
				editorOp : {
					conf : {
						multi : false,
						combo : false
					}
				}
			}, {
				width : 120,
				field : 'control',
				cssName : "center",
				header : 'ccay.sitemap.label.control',
				type : "enum",
				format : {
					service : 'FN:Ccay.SiteMap.ListSiteMap.getControlData',
					valueField : "value",
					displayField : "text"
				},
				rule : {
					required : true,
					maxlength : 1000
				}
			}, {
				width : 100,
				field : 'permissionName',
				valueField : "permissionString",
				header : 'ccay.sitemap.label.function',
				rendererType : "ellipsis",
				editorOp : {
					cssName : "grid-editor",
					conf : {
						valueField : 'permissionString',
						displayField : 'permissionName'
					}
				},
				editor : Ccay.Editor.create(popupPermissionTree),
				rule : {
					customRequired : permissionValid
				},
				renderer : Ccay.UI.Renderer.create(showPermissionName)
			}, {
				width : 90,
				field : 'target',
				cssName : "center",
				header : 'ccay.sitemap.label.target',
				type : "enum",
				editorOp : {
					conf : {
						valid : false
					}
				},
				format : {
					service : 'FN:Ccay.SiteMap.ListSiteMap.getTargetSource',
					valueField : "value",
					displayField : "text",
					valid : false
				},
				rule : {
					required : true
				}
			}, {
				width : 115,
				field : 'description',
				header : 'ccay.sitemap.label.description',
				type : "textarea",
				rendererType : "ellipsis",
				rule : {
					maxlength : 1000
				}
			}, {
				width : 115,
				field : 'location',
				header : 'ccay.sitemap.label.location',
				type : "text",
				rendererType : "ellipsis",
				rule : {
					maxlength : 20
				}
			} ],
			ajax : {
				url : "services/manage/sitemap/tree/list"
			},
			operation : {
				search : {
					btn : '#btnSearch',
					panel : '#searchForm'
				}
			// del: {
			// btn: '#btnDelete',
			// undoBtn: '#btnUndoDelete'
			// },
			// insert: {
			// btn: '#btnAdd',
			// defaultRow:{name:'zh_CN=,en_US=',target:'_self',
			// status:'2',control:'1',orderId:'0',parent:{name:workspaceVO.leftMenuNode.name,siteNodeId:workspaceVO.leftMenuNode.siteNodeId}}
			// }
			}
		};
	
		// TODO 是否有insert权限，判断该contextMenu是否显示
		gridOption.operation.del = {
			btn : '#btnDelete',
			undoBtn : '#btnUndoDelete'
		}
		//debugger;
		if (Ccay.Permission.check("Service$SiteMap.Manage$delete")) {
		}
		// TODO 是否有delete权限，判断该contextMenu是否显示
		gridOption.operation.insert = {
			btn : '#btnAdd',
			defaultRow : {
				name : 'zh_CN=,en_US=',
				target : '_self',
				status : '2',
				control : '4',
				orderId : '0',
				parent : {
					name : workspaceVO.leftMenuNode.name,
					siteNodeId : workspaceVO.leftMenuNode.siteNodeId
				}
			}
		}
		if (Ccay.Permission.check("Service$SiteMap.Manage$create")) {
		}
		$S("#listSiteMapIgrid").igrid(gridOption);
	};
	
	// 自定义grid的保存
	page.save = function() {
		var manager = $S("#listSiteMapIgrid").manager();
		// 验证
		if (manager.valid()) {
			var getInsertedRecords = manager.getInsertedRecords(), preDelRecords = manager.op.Storage.getPreDeletedRecords(), getUpdatedRecords = manager.getUpdatedRecords(), getDeletedRecords = manager
					.getDeletedRecords();
			// 无记录更改时，不保存
			if (!preDelRecords.length && !getInsertedRecords.length && !getUpdatedRecords.length && !getDeletedRecords.length) {
				Ccay.UI.topBox("ccay.common.message.nothingModified");
				return false;
			}
			if (getUpdatedRecords.length) {
				for (var i = 0; i < getUpdatedRecords.length; i++) {
					var data = getUpdatedRecords[i];
					if (data.control == 3 && !data.permissionString) {
						manager.showValidResult("", $i18n("ccay.common.validate.required"), manager.getCellByField(data.rowIdx, "permissionString"));
						return false;
					}
				}
			}
			var data = {};
			data.items2Create = getInsertedRecords;
			data.items2Update = getUpdatedRecords;
			data.items2Delete = getDeletedRecords;
			Ccay.doPut("services/manage/sitemap/batch/save", data, function() {
				manager.clearCache();
				manager.request();
			});
		}
	};
	
	// 控制显示栏目
	page.getControlData = function() {
		return [ {
			value : "4",
			text : $i18n("ccay.sitemap.label.public")
		}, {
			value : "1",
			text : $i18n("ccay.sitemap.label.visibleToEveryone")
		},{
			value : "2",
			text : $i18n("ccay.sitemap.label.visibleByChildren")
		}, {
			value : "3",
			text : $i18n("ccay.sitemap.label.visibleToFunction")
		} ]
	};
	
	// 打开方式
	page.getTargetSource = function() {
		return [ {
			value : "_self",
			text : $i18n("ccay.sitemap.label.self")
		}, {
			value : "_blank",
			text : $i18n("ccay.common.button.blank")
		}, {
			value : "_contentFrame",
			text : $i18n("ccay.sitemap.label.iframe")
		}, {
			value : "_website",
			text : $i18n("ccay.sitemap.label.website")
		} ];
	};
	
	// 是否发布
	page.getStatus = function() {
		return [ {
			value : "0",
			text : $i18n("ccay.common.label.no")
		}, {
			value : "2",
			text : $i18n("ccay.common.label.yes")
		} ];
	};
	
	// 栏目弹出树
	var popupTree = {
		build : function(container, op) {
			var ctr = $.create("input", "", $.newGuid("ctr_editor_"), "text").attr('readonly', 'true').appendTo(container);
			var btn = $.create("input", "jbutton", "", "button").attr("value", "...").appendTo(container);
			var bean = op.conf || {};
			btn.click(function() {
				ctr.data("ctr_locked", true);
				// Ccay.Component.popupTree =
				// function(title,dataOrUrl,treeSetting,selectCallback,width,height,dialogOp)
				var currId = $S("#listSiteMapIgrid").manager().getRowData(ctr.data('caller').parents("tr:first")).siteNodeId;
				bean.treeSetting.chkDisableds = [ currId ];
				Ccay.Component.popupTree(bean.title, bean.url, bean.treeSetting, function(nodes) {
					if (nodes.length > 0) {
						ctr.data("value", nodes[0][bean.valueField]).val(nodes[0][bean.displayField]);
					}
				}, null, null, {
					fnClose : function() {
						ctr.removeData("ctr_locked").focus();
					}
				});
			});
			return ctr;
		},
		getValue : function(ctr) {
			return {
				value : ctr.data("value") || "",
				text : ctr.val() || ""
			}
		},
		setValue : function(ctr, valueObj) {
			ctr.data("value", valueObj.value);
			this.base.setValue.call(this, ctr, valueObj.text);
		}
	};
	
	// 权限弹出树
	var popupPermissionTree = {
		build : function(container, op) {
			var ctr = $.create("input", "", $.newGuid("ctr_editor_"), "text").attr('readonly', 'true').appendTo(container);
			var btn = $.create("input", "jbutton", "", "button").attr("value", "...").appendTo(container);
			var bean = op.conf || {};
			btn.click(function() {
				ctr.data("ctr_locked", true);
				Permission.popPermissionTree(false, null, function(result) {
					if (result.length > 0) {
						var permission = result[0];
						ctr.data("value", permission.value).val(permission.text);
					}
					;
				}, ctr.data("value"), {
					beforeClose : function() {
						ctr.removeData("ctr_locked").focus();
					}
				});
			});
			return ctr;
		},
		getValue : function(ctr) {
			return {
				value : ctr.data("value") || "",
				text : ctr.val() || ""
			}
		},
		setValue : function(ctr, valueObj) {
			ctr.data("value", valueObj.value);
			this.base.setValue.call(this, ctr, valueObj.text);
		}
	};
	
	// 设置自定义验证器 特殊字符
	$.validator.addMethod("speczh", function(value, element, params) {
		if (value) {
			var reg = new RegExp("[<>?!@#$%\\\\\\/]+");
			return !reg.test(value) ? true : false;
		}
	}, $i18n("ccay.common.validate.speczh"));
	
	// 菜单弄成渲染
	page.languageRender = function(value) {
		/*
		 * if(value == null){ return ""; }; if(value ==
		 * "zh_CN=,en_US="){ return value; }; var nameLanguage =
		 * value.split(","); var language =
		 * workspaceVO.currentLanguage; for (var i = 0; i <
		 * nameLanguage.length; i++) { var lang =
		 * nameLanguage[i].split("="); if (lang.length > 1 &&
		 * lang[0] == language) { return lang[1]; } }; return
		 * value;
		 */
		return Ccay.Format.formatSpace(Ccay.DataHelper.languageExtraction(value));
	};
	
	// 节点名渲染器
	var showNameByLang = {
		type : "sitemap", // 树表showField和渲染的是同一列导致自定义渲染器无效，需加上type解决，任意字符串
		setOption : function(op) {
			op.valueField = op.field;
			this.base.setOption.call(this, op);
		},
		getFormat : function(field, format) {
			return "${#Ccay.SiteMap.ListSiteMap.languageRender({0})}".formatText(field);
		},
		render : function(target, value, format) {
			target.find(".child-render").html(this.format(value, format)).attr("title", value);
		},
		getValue : function(target) {
			//以编辑过的数据为准
			var child = target.children(".child-render");
			if (child.attr("title")) {
				return child.text();
			} else {
				return target.attr("val");
			}
		}
	};
	
	// 父节点名渲染器
	var showNameByLang2p = {
		getFormat : function(field, format) {
			return "${#Ccay.SiteMap.ListSiteMap.languageRender({0})}".formatText(field);
		},
		getValue : function(target) {
			return {
				value : target.attr('val') || "",
				text : target.text() || ""
			};
		},
		format : function(value, format) {
			if (!format)
				format = {};
			return Ccay.SiteMap.ListSiteMap.languageRender(value);
		},
		render : function(target, valueObj, format) {
			target.attr('val', valueObj.value);
			target.html(this.format(valueObj.text, format));
		}
	};
	
	// 权限渲染器
	var showPermissionName = {
		getValue : function(target) {
			return {
				value : target.attr('val') || "",
				text : target.text() || ""
			};
		},
		render : function(target, valueObj, format) {
			target.attr('val', valueObj.value);
			target.html(valueObj.text);
		}
	};
	
	// siteNode 导入
	page.siteMapImport = function() {
		var param = {
			uploadType : "ExcelImport",
			completeCallback : Ccay.Component.Excel.uploadCallback,
			closeDialog : true,
			query : "excelType=ccay.sitemap.siteNode"
		};
		Ccay.Component.openUploadDialog("ccay.common.button.import", param);
	}
	
	// siteNode 导出全部
	page.siteMapExport = function(nodeId) {
		if (nodeId == null) {
			nodeId = 0;
		}
		;
		Ccay.doGet("services/manage/sitemap/list/export", {
				siteNodeId : nodeId
			}, function() {
				Ccay.Component.Excel.exportCallback();
			});
		};

});
